import 'package:flutter/material.dart';
import 'package:flutter_ns_ble/flutter_ns_ble.dart';
import 'package:path_provider/path_provider.dart';

class SyncDataPage extends StatelessWidget {
  final Peripheral peripheral;
  const SyncDataPage({super.key, required this.peripheral});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("同步数据")),
      body: StreamBuilder(
        stream: peripheral.b1SyncDataState,
        builder: (context, snapshot) {

          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text("同步数据:${snapshot.data?.state}"),
                Text("receivedSize:${(snapshot.data)?.receivedSize}"),
                Text("totalSize:${(snapshot.data)?.totalSize}"),
                Text("stateCode:${(snapshot.data)?.stateCode}"),
                Text("errorMsg:${(snapshot.data)?.errorMsg}"),
                if (snapshot.data?.state == B1SyncDataState.idle ||
                    snapshot.data?.state == B1SyncDataState.canceled ||
                    snapshot.data?.state == B1SyncDataState.completed)
                  ElevatedButton(
                    onPressed: () async {
                      var file = await peripheral.startB1SyncData(deleteBeforeWrite: true);
                      var dir = await getApplicationCacheDirectory();
                      var target = dir.path + "/b1_sync_data.txt";
                      final reader = B1SyncDataReader(sourceFilePath: file!, targetFilePath: target);
                      await for (var progress in reader.process()) {
                        print(progress);
                      }
                    },
                    child: Text("同步数据"),
                  ),
                if (snapshot.data?.state == B1SyncDataState.progress)
                  ElevatedButton(
                    onPressed: () {
                      peripheral.cancelB1SyncData();
                    },
                    child: Text("取消同步"),
                  ),

              ],
            ),
          );
        },
      ),
    );
  }
}
